package com.guaju.yueshangLife.adapter;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.activity.GoodsDetailActivity;
import com.guaju.yueshangLife.bean.Goods;
import com.guaju.yueshangLife.databinding.FooterItemBinding;
import com.guaju.yueshangLife.utils.ToastUtil;

import java.util.IllegalFormatCodePointException;
import java.util.List;

/**
 * Created by guaju on 2018/8/6.
 */
public class CommonRecyclerViewAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


    public static final String GOODS_ID = "goods_id";
    private int status = LOAD_LESS;
    public static final int LOAD_MORE = 0;
    public static final int LOAD_PULL_TO = 1;
    public static final int LOAD_NONE = 2;
    public static final int LOAD_END = 3;
    public static final int LOAD_LESS = 4;

    private static final int TYPE_FOOTER = -2;
    private static final int TYPE_CONTENT = -4;

    Context context;
    LayoutInflater layoutInflater;
    int layoutId;
    int variableId;
    List<T> lists;
    public  OnItemClickListener onItemClickListener;


    public CommonRecyclerViewAdapter(Context context, LayoutInflater layoutInflater, int layoutId, int variableId, List<T> lists) {
        this.context = context;
        this.layoutInflater = layoutInflater;
        this.layoutId = layoutId;
        this.variableId = variableId;
        this.lists = lists;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        switch (viewType) {
            case TYPE_FOOTER:
                FooterItemBinding mBindFooter = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.footer_item, parent, false);
                return new FooterViewHolder(mBindFooter.getRoot());
            default:
                //先得到viewdatabinding对象，这个对象中会持有条目item 布局的引用
                ViewDataBinding viewDataBinding = DataBindingUtil.inflate(layoutInflater, layoutId, parent, false);
                //***切记，一定要使用viewdatabinding中的view的引用去实例化viewholder对象，否则将不会有任何效果
                CommonViewHolder commonViewHolder = new CommonViewHolder(viewDataBinding.getRoot().getRootView());
                //为下文中的onBindViewHolder方法进行铺垫，即让viewholder与viewdatabinding捆绑在一起（注意setBinding是我们自己提供的方法）
                commonViewHolder.setBinding(viewDataBinding);
                return commonViewHolder;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

       if (holder instanceof CommonRecyclerViewAdapter.FooterViewHolder) {
            FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
            footerViewHolder.bindItem();
        } else if (holder instanceof CommonRecyclerViewAdapter.CommonViewHolder) {
            CommonViewHolder commonViewHolder = (CommonViewHolder) holder;
            if (lists != null && lists.size() > 0) {
                commonViewHolder.setContent(lists.get(position));
//                commonViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        if (onItemClickListener!=null){
//                            onItemClickListener.onClick(position);
//                        }
//                    }
//                });

                commonViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ToastUtil.show(lists.get(position)+"");
                        T t = lists.get(position);
                        if (t instanceof Goods){
                            Goods goods=(Goods)t;
                            Intent intent = new Intent(context, GoodsDetailActivity.class);
                            intent.putExtra(GOODS_ID,goods.getId());
                            context.startActivity(intent);
                        }
                    }
                });
            }
        }


    }


    @Override
    public int getItemCount() {
        return lists.size() + 1;
    }

    /**
     * 处理 GridLayoutManager 添加头尾布局占满屏幕宽的情况
     */
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof GridLayoutManager) {
            final GridLayoutManager gridManager = ((GridLayoutManager) manager);
            gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return (isFooter(position)) ? gridManager.getSpanCount() : 1;
                }
            });
        }
    }

    /**
     * 处理 StaggeredGridLayoutManager 添加头尾布局占满屏幕宽的情况
     */
    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
        if (lp != null
                && lp instanceof StaggeredGridLayoutManager.LayoutParams
                && (isFooter(holder.getLayoutPosition()))) {
            StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
            p.setFullSpan(true);
        }
    }


    public class CommonViewHolder extends RecyclerView.ViewHolder {
        //以前是定义一堆控件，现在呢?定义一下viewdatabinding ,用它去设置变量
        ViewDataBinding viewDataBinding;

        public CommonViewHolder(View itemView) {
            super(itemView);
        }

        public void setBinding(ViewDataBinding binding) {
            viewDataBinding = binding;
        }

        public ViewDataBinding getBinding() {
            return viewDataBinding;
        }

        public void setContent(T t) {
            viewDataBinding.setVariable(variableId, t);
//          必须加上，这会强制绑定操作马上执行，而不是推迟到下一帧刷新时，
//          RecyclerView 会在 onBindViewHolder 之后立即测量 View。
//          如果因为绑定推迟到下一帧绘制时导致错误的数据被绑定到 View 中, View 会被不正确地测量，
            viewDataBinding.executePendingBindings();
        }
    }


    @Override
    public int getItemViewType(int position) {

        if (position + 1 == getItemCount()) {
            return TYPE_FOOTER;
        } else {
            return TYPE_CONTENT;
        }
    }

    public void updateLoadStatus(int status) {
        this.status = status;
        notifyDataSetChanged();
    }

    public int getLoadStatus() {
        return this.status;
    }


    /**
     * footer view
     */
    private class FooterViewHolder extends RecyclerView.ViewHolder {

        FooterItemBinding mBindFooter;

        FooterViewHolder(View itemView) {
            super(itemView);
            mBindFooter = DataBindingUtil.getBinding(itemView);
            mBindFooter.rlMore.setGravity(Gravity.CENTER);
//            LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtils.dipToPx(context, 40));
//            itemView.setLayoutParams(params);
        }

        private void bindItem() {
            switch (status) {
                case LOAD_MORE:
                    mBindFooter.rlMore.setVisibility(View.VISIBLE);
                    mBindFooter.progress.setVisibility(View.VISIBLE);
                    mBindFooter.tvLoadPrompt.setText("正在加载...");
                    itemView.setVisibility(View.VISIBLE);
                    break;
                case LOAD_PULL_TO:
                    mBindFooter.rlMore.setVisibility(View.VISIBLE);
                    mBindFooter.progress.setVisibility(View.GONE);
                    mBindFooter.tvLoadPrompt.setText("上拉加载更多");
                    itemView.setVisibility(View.VISIBLE);
                    break;
                case LOAD_NONE:
                    mBindFooter.rlMore.setVisibility(View.VISIBLE);
                    mBindFooter.progress.setVisibility(View.GONE);
                    mBindFooter.tvLoadPrompt.setText("暂无数据");
                    break;
                case LOAD_END:
                    mBindFooter.rlMore.setVisibility(View.VISIBLE);
                    mBindFooter.progress.setVisibility(View.GONE);
                    mBindFooter.tvLoadPrompt.setText("没有更多内容了");
                case LOAD_LESS:
                    mBindFooter.rlMore.setVisibility(View.GONE);
                default:
                    break;
            }
        }
    }
    /**
     * 这里规定 position =  getItemCount() - 1 时
     * 就为尾布局，设置为占满整屏幕宽
     * getItemCount() 改了 ，这里就不用改
     */
    private boolean isFooter(int position) {
        return position < getItemCount() && position >= getItemCount() - 1;
    }

    public List<T> getLists() {
        return lists;
    }

    public void setList(List<T> list) {
        this.lists.clear();
        this.lists = list;
    }

    public void addAll(List<T> list) {
        this.lists.addAll(list);
    }

    private interface OnItemClickListener {

        void onClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
}

